package com.gimi.cloud.bbp.merchantZone.service.store.impl;

import com.gimi.cloud.bbp.common.utils.MyBeanUtils;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.UUIDUtil;
import com.gimi.cloud.bbp.dao.dao.stroe.MerchantRengeDao;
import com.gimi.cloud.bbp.dao.dao.stroe.StoreDao;
import com.gimi.cloud.bbp.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.bbp.dto.prod.EcProdCategoryDTO;
import com.gimi.cloud.bbp.dto.store.MerchantRangeDTO;
import com.gimi.cloud.bbp.dto.store.StoreDTO;
import com.gimi.cloud.bbp.entity.store.MerchantRangeEntity;
import com.gimi.cloud.bbp.entity.store.StoreEntity;
import com.gimi.cloud.bbp.merchantZone.service.product.ProductService;
import com.gimi.cloud.bbp.merchantZone.service.store.StoreService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * Created by shazhiwei on 2017/12/20.
 */
@Service
public class StoreServiceImpl implements StoreService {
    private final StoreDao storeDao;

    private final MerchantRengeDao merchantRengeDao;

    private final ProductService productService;

    public StoreServiceImpl(StoreDao storeDao,MerchantRengeDao merchantRengeDao,ProductService productService){
        this.storeDao = storeDao;
        this.merchantRengeDao = merchantRengeDao;
        this.productService = productService;
    }

    /**
     * 添加商铺
     * @param storeDTO
     * @return
     */
    @Override
    public Boolean addStore(StoreDTO storeDTO) {
        storeDTO.setStoreId(UUIDUtil.get32UUID());
        storeDTO.setStoreCreateTime(new Date());//设置店铺注册时间
        storeDTO.setMarketType(1);
        storeDTO.setStoreStatus(2);//设置审核状态为审核中
        //验证店铺名称是否存在
        List<StoreEntity> stores = storeDao.storeExists(storeDTO.getStoreName(),storeDTO.getMerchantId());
        if(null!= stores && stores.size()>0){
            return false;
        }
        StoreEntity entity = new StoreEntity();
        MyBeanUtils.copyPropertiesIgnoreNull(storeDTO,entity);
        return storeDao.baseInsert(entity)>0;
    }

    /**
     * 条件查询商铺
     * @param storeDTO
     * @return
     */
    /*@Override
    public PageInfo<StoreDTO> getStoreListByCondition(StoreDTO storeDTO) {
        PageHelper.startPage(storeDTO.getCurrentPage(), storeDTO.getPageSize());
        Example example = new Example(StoreEntity.class);
        Example.Criteria criteria = example.createCriteria();
        //非删除的商铺
        if(StringUtil.isBlank(storeDTO.getStoreName())){
            criteria.andNotEqualTo("isDelete","1");
        }else {
            criteria.andNotEqualTo("isDelete","1")
                    .andLike("storeName","%"+storeDTO.getStoreName()+"%");
        }
        List<StoreEntity> datas = storeDao.selectByExample(example);
        List<StoreDTO> results = new ArrayList<>();
        for(StoreEntity entity : datas){
            StoreDTO dto = new StoreDTO();
            MyBeanUtils.copyProperties(entity,dto);
            results.add(dto);
        }
        PageInfo<StoreDTO> page = new PageInfo<>(results);
        return page;
    }*/

    @Override
    public Map<String,Object> getStoreListByCondition(StoreDTO storeDTO) {
        Map<String,Object> result = new HashMap<>();
        String where = StringUtil.isBlank(storeDTO.getStoreName()) ? "is_delete = 0"
                : String.format("is_delete = 0 AND store_name LIKE %s","CONCAT('%','" + storeDTO.getStoreName() + "','%')");
        int count = storeDao.getCountBySql(String.format("SELECT count(1) FROM ec_store WHERE %s",where));
        Integer limit = storeDTO.getPageSize();
        Integer offset = (storeDTO.getCurrentPage() - 1) * limit;
        String sql = "SELECT * FROM ec_store WHERE %s LIMIT %d,%d";
        List<StoreDTO> list = storeDao.selectBySql(String.format(sql,where,offset,limit));
        result.put("count",count);
        result.put("list",list);
        return result;
    }

    @Override
    public List<StoreDTO> allStoreList(StoreDTO storeDTO) {
        return storeDao.allStoreList(storeDTO.getMerchantId());
    }

    /**
     * 条件获取单个店铺
     * @param storeDTO
     * @return
     */
    @Override
    public StoreDTO getStoreSingleByCondition(StoreDTO storeDTO) {
        StoreEntity entity = storeDao.selectByPrimaryKey(storeDTO.getStoreId());
        StoreDTO dto = new StoreDTO();
        MyBeanUtils.copyProperties(entity,dto);
        return dto;
    }

    /**
     * 店铺审核
     * @param storeDTO
     * @return
     */
    @Override
    public Boolean storeAuth(StoreDTO storeDTO) {
        QueryParam param = new QueryParam();
        String sql = "update ec_store set store_status =:storeStatus,audit_time=:auditTime,auditor=:auditor where store_id = :storeId ";
        storeDTO.setAuditTime(storeDTO.getUpdateTime());
        storeDTO.setAuditor(storeDTO.getUpdateUname());
        param.setParamObject(storeDTO);
        param.setSql(sql);
        return storeDao.updateSql(param)>0;
    }


    /**
     * 更新店铺
     * @param storeDTO
     * @return
     */
    @Override
    public Boolean updateStore(StoreDTO storeDTO) {
        List<StoreEntity> stores = storeDao.storeExists(storeDTO.getStoreName(),storeDTO.getMerchantId());
        if(null!=stores && stores.size()>0) {
            StoreEntity store = stores.get(0);
            if (!store.getStoreId().equals(storeDTO.getStoreId())) {
                return false;
            }
        }
        StoreEntity entity = storeDao.selectByPrimaryKey(storeDTO.getStoreId());
        MyBeanUtils.copyPropertiesIgnoreNull(storeDTO,entity);
        entity.setUpdateTime(new Date());
        entity.setUpdateUid(storeDTO.getUpdateUid());
        return storeDao.updateByPrimaryKey(entity)>0;
    }

    /**
     * 删除店铺
     * @param storeDTO
     * @return
     */
    @Override
    public Boolean deleteStore(StoreDTO storeDTO) {
        StoreEntity entity = storeDao.selectByPrimaryKey(storeDTO.getStoreId());
        if (entity != null) {
            //删除经营范围
            this.deleteMerchantRangeByStoreId(entity.getStoreId());
            //删除店铺
            entity.setIsDelete(1);//设置删除属性
            return storeDao.updateByPrimaryKey(entity) > 0;
        }
        return false;
    }

    /**
     * 添加店铺经营范围
     * @param dto
     * @return
     */
    @Override
    public Boolean addStoreManchant(MerchantRangeDTO dto) {
        String[] categoryIds = dto.getProdCatId().split(",");
        for(String categoryId : categoryIds){
            MerchantRangeEntity entity = new MerchantRangeEntity();
            MyBeanUtils.copyProperties(dto,entity);
            entity.setProdCatId(categoryId);
            entity.setStatus(2);
            entity.setVersion(0);
            entity.setIsDelete(0);
            merchantRengeDao.insert(entity);
        }
        return true;
    }

    @Override
    public Boolean updateStoreManchant(MerchantRangeDTO dto) {
        return null;
    }

    /**
     * 获取店铺经营范围
     * @param dto
     * @return
     */
    @Override
    public List<MerchantRangeDTO> getMerchantRangeListByCondition(MerchantRangeDTO dto) {
        String sql = " select t.*,t1.prod_cat_name from ec_merchant_range t " +
                     " left join ec_prod_category t1 on t.prod_cat_id = t1.prod_cat_id " +
                     " where 1=1 and t.is_delete=0 and t.store_id=:storeId ";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(dto);
        return merchantRengeDao.getMerchantRangeListByCondition(queryParam);
    }

    /**
     * 获取店铺可添加的经营范围
     * @param dto
     * @return
     */
    @Override
    public List<Map<String,Object>> getProCategoreListByCondition(MerchantRangeDTO dto) {
        //查询排除掉当前已选经营范围的数据
        String sql = " select * from ec_prod_category where prod_cat_id not in " +
                     " (select prod_cat_id from ec_merchant_range where 1=1 and is_delete=0 and store_id=:storeId) ";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(dto);
        List<EcProdCategoryDTO> cates = merchantRengeDao.getProCategoreListByCondition(queryParam);
        return productService.toTree(cates,1,null);
    }

    /**
     * 删除店铺经营范围
     * @param dto
     * @return
     */
    @Override
    public Boolean deleteMerchantRange(MerchantRangeDTO dto) {
        return merchantRengeDao.deleteByPrimaryKey(dto.getMrId())>0;
    }


    /**
     * 通过店铺Id删除经营范围
     * @param storeId
     * @return
     */
    @Override
    public int deleteMerchantRangeByStoreId(String storeId){
        Example example = new Example(MerchantRangeEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId",storeId);
        return merchantRengeDao.deleteByExample(example);
    }
}
